package hu.farago.wsj.parse.wordprocess;

import hu.farago.wsj.model.entity.Article;
import hu.farago.wsj.model.entity.ArticleWord;

import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

@Service("regex")
public class RegexWordsProcessor implements WordsProcessor {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(RegexWordsProcessor.class);
	
	private Pattern pattern = Pattern.compile("([a-zA-Z_]+-?[a-zA-Z_]+('[a-rt-zA-RT-Z]{1,2})?)|(i|I|a|A)");

	@Override
	public void parseArticlePlainTextAndBuildMapOfWords(Article existingArticle) {
		Assert.notNull(existingArticle);
		Assert.notNull(existingArticle.getPlainText());
		
		existingArticle.setArticleWords(new HashSet<ArticleWord>());
		
		Matcher matcher = pattern.matcher(existingArticle.getPlainText());
		
		while (matcher.find()) {
			String str = matcher.group();
			if (StringUtils.isNotBlank(str)) {
				addWordToArticle(existingArticle, str);
			}	
		}
	}

	private void addWordToArticle(Article existingArticle, String word) {
		LOGGER.debug(word);
		ArticleWord articleWord = new ArticleWord();
		articleWord.setWord(StringUtils.lowerCase(word));
		existingArticle.addArticleWord(articleWord);
	}

}
